<template>
  <div>
    <!--面包屑导航-->
    <Breadcrumb>
      <template #firstTitle>
        <span>权限管理</span>
      </template>
      <template #secondTitle>
        <span>角色列表</span>
      </template>
    </Breadcrumb>
    <!--卡片视图-->
    <el-card>
      <!--添加角色-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--用户列表-->
      <el-table
        border
        stripe
        :data="rolesList">
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', index1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!--一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <!--通过for循环嵌套渲染二级权限-->
                <el-row :class="[index2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="18">
                    <!--通过for循环嵌套渲染三级权限-->
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="290">
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
            <!--删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteOpen(scope.row.id)">删除</el-button>
            <!--分配权限按钮-->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
      width="50%">
      <!--内容主体-->
      <el-form
        status-icon
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px">
        <!--角色名称-->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <!--角色描述-->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--内容底部-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolse">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改角色对话框-->
    <el-dialog
      title="修改角色"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
      width="50%">
      <!--内容主体-->
      <el-form
        status-icon
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px">
        <!--角色名称-->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <!--角色描述-->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!--内容底部-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRolse">确 定</el-button>
      </span>
    </el-dialog>

    <!--分配权限对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      lock-scroll
      @close="setRightDialogClosed"
      width="50%">
      <!--内容主体-->
      <el-tree
        :data="rightsList"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        :props="treeProps"
        ref="treeRef">
      </el-tree>
      <!--内容底部-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Breadcrumb from '@/components/common/Breadcrumb.vue'

  export default {
    name: "Roles",
    data(){
      return{
        // 所有角色列表数据
        rolesList: [],
        // 控制分配权限对话框的显示与隐藏
        setRightDialogVisible: false,
        // 所有权限列表
        rightsList: [],
        // 树形控件的属性绑定对象
        treeProps: {
          children: 'children',
          label: 'authName'
        },
        // 默认选中的节点ID值数组
        defKeys: [],
        // 当前分配权限的角色ID
        roleId: '',
        addDialogVisible: false,  //控制添加角色对话框的显示和隐藏
        addForm: {  //添加角色表单数据
          roleName: '',
          roleDesc: ''
        },
        addFormRules: { //添加表单的校验规则
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],
          roleDesc: [
            {required: true, message: '请输入角色描述', trigger: 'blur'}
          ]
        },
        editDialogVisible: false, //控制修改角色信息对话框的显示和隐藏
        editForm: {},  //查询到的角色信息数据
        editFormRules: {  //修改表单的校验规则
          roleName: [
            {required: true, message: '请输入角色名称', trigger: 'blur'}
          ],
          roleDesc: [
            {required: true, message: '请输入角色描述', trigger: 'blur'}
          ]
        },
      }
    },
    components: {
      Breadcrumb
    },
    created() {
      this.getRolesList();
    },
    methods: {
      // 获取用户列表
      async getRolesList() {
        const {data: res} = await this.$http.get('roles');
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(`获取角色列表: ${res.meta.msg}`);
          return;
        }
        this.rolesList = res.data;
      },
      // 根据ID删除对应的权限
      removeRightById(role, rightId){
        this.$confirm('此操作将永久删除该权限, 是否继续?', '删除权限', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
          // console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('删除失败');
            return;
          }
          this.$message.success('删除成功!');
          role.children = res.data;
        }).catch(() => {
          this.$message.info('已取消删除');
        });
      },
      // 展示分配权限的对话框
      async showSetRightDialog(role){
        this.roleId = role.id;
        // 获取所有权限的数据
        const {data: res} = await this.$http.get('rights/tree');
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(`获取权限列表: ${res.meta.msg}`);
          return;
        }
        this.rightsList = res.data;
        // 递归获取三级节点ID
        this.getLeafKeys(role, this.defKeys);
        this.setRightDialogVisible = true;
      },
      // 监听分配权限对话框关闭事件
      setRightDialogClosed(){
        this.defKeys = [];
      },
      // 点击确定为角色分配权限
      async allotRights(){
        const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys(),
        ];
        const idStr = keys.join(',');
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`, {rids: idStr});
        // console.log(res);
        if (res.meta.status !== 200) {
          this.$message.error(`分配权限失败: ${res.meta.msg}`);
          return;
        }
        this.$message.success(`分配权限成功`);
        this.getRolesList();
        this.setRightDialogVisible = false;
      },
      // 通过递归形式获取角色下所有三级权限的ID，并保存到defKeys数组中
      getLeafKeys(node, arr){
        // 如果当前node节点不包含children属性则是三级节点
        if(!node.children){
          return arr.push(node.id);
        }
        node.children.forEach(item => {
          this.getLeafKeys(item, arr)
        })
      },
      // 监听添加角色对话框关闭
      addDialogClosed() {
        this.$refs.addFormRef.resetFields();
      },
      // 添加角色
      addRolse() {
        this.$refs.addFormRef.validate(async (valid) => {
          if (!valid) return;
          // 可以发起添加角色请求
          const {data: res} = await this.$http.post('roles', this.addForm);
          // console.log(res);
          if (res.meta.status !== 201) {
            this.$message.error('添加角色失败');
            this.addDialogVisible = false;
            return;
          }
          this.$message.success('添加角色成功');
          this.addDialogVisible = false;
          this.getRolesList();
        });
      },
      // 展示修改角色信息对话框
      showEditDialog(row) {
        console.log(row);
        this.editForm = row;
        this.editDialogVisible = true;
      },
      // 监听修改角色对话框关闭
      editDialogClosed() {
        this.$refs.editFormRef.resetFields();
      },
      // 修改角色信息并提交
      editRolse() {
        this.$refs.editFormRef.validate(async (valid) => {
          if (!valid) return;
          // 可以发起修改用户信息请求
          const {data: res} = await this.$http.put(`roles/${this.editForm.id}`, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          });
          // console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('修改角色信息失败');
            this.editDialogVisible = false;
            return;
          }
          this.$message.success('修改角色信息成功');
          this.editDialogVisible = false;
          this.getRolesList();
        });
      },
      // 删除角色提示对话框
      deleteOpen(id) {
        this.$confirm('此操作将永久删除该角色数据, 是否继续?', '删除角色信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {data: res} = await this.$http.delete(`roles/${id}`);
          // console.log(res);
          if (res.meta.status !== 200) {
            this.$message.error('删除角色信息失败');
            return;
          }
          this.$message.success('删除角色信息成功!');
          this.getRolesList();
        }).catch(() => {
          this.$message.info('已取消角色信息删除');
        });
      }
    }
  }
</script>

<style scoped>
  .el-tag{
    margin: 8px;
  }
  .bdtop{
    border-top: 1px solid #eeeeee;
  }
  .bdbottom{
    border-bottom: 1px solid #eeeeee;
  }
  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
